<script setup lang="ts">
import { getCurrentInstance, ref, reactive, watch, onMounted, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import '@ckeditor/ckeditor5-build-classic/build/translations/zh-cn'
import CKEditor from '@ckeditor/ckeditor5-build-classic'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
let isFirst = true
let cates = []
let cateRoots = []
const cateSons = ref([])
let units = []
const psize = ref([{
  name: '',
  cloudprice: '',
  price: '',
  unit: 0
}])
const isFromCloud = ref(false)
// ----
const top = reactive({
  add: true,
  maxnum: 0,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    aspectRatio: 1,
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
const fot = reactive({
  add: true,
  maxnum: 0,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
// ----
let myEditor = null
// ----
const isAmount = /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{2}$)/
const form = reactive({
  name: '',
  cateRootTxt: '',
  cateRoot: 0,
  cateSonTxt: '',
  cateSon: 0,
  unitTxt: '',
  unit: 0,
  noteTxt: '',
  content: ''
})

/* ---- */
const pickerCateRoot = ref()
const pickerCateSon = ref()
const pickerUnit = ref()
const uploadoss = ref()
const layer = ref()
const layerLoading = ref()

/* ---- */
const initEditor = () => {
  CKEditor.create(proxy.$refs.forEditor, {
    language: 'zh-cn',
    toolbar: ['heading', '|', 'fontColor', 'fontBackgroundColor', '|', 'bold', 'italic', '|', 'indent', 'outdent', '|', 'blockQuote', 'insertImage', 'insertTable', 'mediaEmbed', 'undo', 'redo']
  }).then((editor) => { myEditor = editor }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err.stack) })
}
// ----
const getFormInfo = async (callback) => {
  top.setTrueStyle = { height: `${document.querySelector('.powerBox dl dd label').clientWidth / top.forFree}px` }
  fot.setTrueStyle = { height: `${document.querySelector('.squareBox dl dd label').clientWidth / fot.forFree}px` }
  // -- 获取商品分类 & 计量单位 --
  const forCateData = {
    params: {
      'ProCategorySearch[dealer_id]': logUser.id,
      // --是否云仓分类--
      'ProCategorySearch[is_store]': 0,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  const forUnitData = {
    params: {
      'MeasuringUnitSearch[dealer_id]': logUser.id,
      // --是否云仓计量单位--
      'MeasuringUnitSearch[is_store]': 0,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('pro-category/index', forCateData),
    proxy.$Axios.get('measuring-unit/index', forUnitData)
  ]).then(proxy.$Axios.spread((cateData, unitData) => {
    // --商品分类--
    cates = cateData.items
    const cateItems = cates.filter((item) => { return Number(item.parent_id) === 0 })
    const rootItems = []
    cateItems.forEach((item, index) => {
      rootItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    cateRoots = rootItems
    // --计量单位--
    const unitItems = []
    unitData.items.forEach((item, index) => {
      unitItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    units = unitItems
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // --商品详情--
  if (proxy.$route.query.id) {
    await proxy.$http.get('proc/index', {
      params: { 'ProductSearch[id]': proxy.$route.query.id }
    }).then((res) => {
      const GData = res.items[0] || {}
      if (GData.name) form.name = GData.name
      form.noteTxt = GData.proremark_id
      form.content = GData.content
      // ----
      proxy.$Myfun.getJsonData(GData.price_json, (resJson) => { psize.value = resJson })
      // ----
      form.cateRoot = GData.parent_id
      cateRoots.some((current) => {
        if (String(current.value) === String(form.cateRoot)) form.cateRootTxt = current.text
      })
      form.cateSon = GData.pro_category_id
      setTimeout(() => {
        cateSons.value.some((current) => {
          if (String(current.value) === String(form.cateSon)) form.cateSonTxt = current.text
        })
      }, 50)
      // ----
      units.some((current) => {
        if (String(current.value) === String(psize.value[0].unit)) form.unitTxt = current.text
      })
      // ----
      isFromCloud.value = Number(GData.is_type) === 1
      // ----
      proxy.$Myfun.getJsonData(GData.img_top, (resJson) => {
        resJson.forEach((item) => {
          top.imgs.push({
            imgName: item.name,
            imgUrl: item.image,
            imgW: item.width,
            imgH: item.height
          })
        })
        if (Number(top.imgs.length) >= Number(top.maxnum) && Number(top.maxnum) > 0) top.add = !top.add
      })
      // ----
      proxy.$Myfun.getJsonData(GData.img_bot, (resJson) => {
        resJson.forEach((item) => {
          fot.imgs.push({
            imgName: item.name,
            imgUrl: item.image,
            imgW: item.width,
            imgH: item.height
          })
        })
        if (Number(fot.imgs.length) >= Number(fot.maxnum) && Number(fot.maxnum) > 0) fot.add = !fot.add
      })
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // ----
  callback && callback()
}
// --上传图片操作--
const uploadAct = (type, selectObj, event, index) => {
  const uploadOss = uploadoss.value
  switch (Number(type)) {
    case 1: {
      uploadOss.uploadImg(event, selectObj,'imgs', index)
      break
    }
    case 2: {
      uploadOss.delInfo(selectObj, event)
      break
    }
    case 3: {
      uploadOss.uploadImgMoreWX(selectObj)
      break
    }
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
const checkLimit = (event, reg, info) => {
  const curEL = event.currentTarget
  if (Number(curEL.value.length) === 0) return false
  if (!reg.test(curEL.value)) {
    if (info) proxy.$Myfun.forToast(layer.value, 'open', info)
    // ----
    curEL.value = ''
    curEL.dispatchEvent(new Event('input'))
  }
}
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const options = {
        type: 1,
        button: ['取消', '确定'],
        initData: cateRoots,
        yes: (result) => {
          if (Number(result.length) > 0) {
            form.cateRootTxt = result[0].text
            form.cateRoot = result[0].value
          }
        }
      }
      proxy.$Myfun.isIndepth(pickerCateRoot.value, 'open', options)
      break
    }
    case 2: {
      const options = {
        type: 1,
        isFirst: isFirst,
        button: ['取消', '确定'],
        initData: cateSons.value,
        yes: (result) => {
          form.cateSonTxt = result[0].text
          form.cateSon = result[0].value
          // ----
          isFirst = false
        }
      }
      proxy.$Myfun.isIndepth(pickerCateSon.value, 'open', options)
      break
    }
    case 3: {
      const options = {
        type: 1,
        button: ['取消', '确定'],
        initData: units,
        yes: (result) => {
          form.unitTxt = result[0].text
          form.unit = result[0].value
        }
      }
      proxy.$Myfun.isIndepth(pickerUnit.value, 'open', options)
      break
    }
    case 4: {
      if (Number(item) > 0) { psize.value.splice(item, 1) } else {
        psize.value.push({
          name: '',
          cloudprice: '',
          price: '',
          unit: form.unit
        })
      }
      break
    }
  }
}
// ----
const subform = async () => {
  if (Number(form.name.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写商品名称！')
    return false
  }
  if (Number(form.cateRootTxt.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择商品一级分类！')
    return false
  }
  if (Number(cateSons.value.length) > 0 && Number(form.cateSonTxt.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择商品二级分类！')
    return false
  }
  if (Number(form.unitTxt.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择计量单位！')
    return false
  }
  for (let i = 0; i < psize.value.length; i++) {
    if (Number(psize.value[i].name.length) === 0 || Number(psize.value[i].price.length) === 0) {
      proxy.$Myfun.forToast(layer.value, 'open', '请设置商品类型、价格！')
      return false
    }
  }
  if (Number(top.imgs.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请上传至少一张商品主图！')
    return false
  }
  // ----
  let topImgs = ''
  if (Number(top.imgs.length) > 0) {
    const topItems = []
    top.imgs.forEach((item) => {
      topItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
    topImgs = JSON.stringify(topItems)
  }
  // ----
  let fotImgs = ''
  if (Number(fot.imgs.length) > 0) {
    const fotItems = []
    fot.imgs.forEach((item) => {
      fotItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
    fotImgs = JSON.stringify(fotItems)
  }
  // ----
  const forPsize = JSON.stringify(psize.value)
  // ----
  let forType = 'post'
  let forUrl = 'proc/create'
  let forData = {
    dealer_id: logUser.id || undefined,
    // ----
    name: form.name,
    parent_id: form.cateRoot,
    pro_category_id: form.cateSon,
    content: myEditor.getData(),
    img_top: topImgs,
    img_bot: fotImgs,
    price_json: forPsize,
    proremark_id: form.noteTxt,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (proxy.$route.query.id) {
    forType = 'patch'
    forUrl = 'proc/update?id=' + proxy.$route.query.id
    forData = {
      name: form.name,
      parent_id: form.cateRoot,
      pro_category_id: form.cateSon,
      content: myEditor.getData(),
      img_top: topImgs,
      img_bot: fotImgs,
      price_json: forPsize,
      proremark_id: form.noteTxt,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'close')
  if (resData) proxy.$router.back()
}
const goback = () => { proxy.$router.back() }

/* ---- */
watch(() => form.unit, (newVal, oldVal) => {
  psize.value.forEach((item) => {
    item.unit = newVal
  })
}, { deep: true })
watch(() => form.cateRootTxt, (newVal, oldVal) => {
  form.cateSonTxt = ''
  form.cateSon = (!oldVal || Number(oldVal.length) === 0) ? form.cateSon : 0
  cateSons.value = []
  isFirst = true
  // ----
  if (Number(newVal.length) === 0) {
    form.cateRoot = 0
  } else {
    const cateItems = cates.filter((item) => { return Number(form.cateRoot) > 0 && Number(item.parent_id) === Number(form.cateRoot) })
    const sonItems = []
    cateItems.forEach((item, index) => {
      sonItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    cateSons.value = sonItems
  }
}, { deep: true })

/* ---- */
onMounted(() => {
  getFormInfo(() => setTimeout(() => { initEditor() }, 300))
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-are xw-radius-3">
            <h1>商品名称</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.name"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>一级分类</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.cateRootTxt" @click="getAuditFun(1)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.cateRootTxt"></em></transition>
          </div>
        </li>
        <li v-if="Number(cateSons.length) > 0">
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>二级分类</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.cateSonTxt" @click="getAuditFun(2)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.cateSonTxt"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>计量单位</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.unitTxt" @click="getAuditFun(3)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.unitTxt"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-price xw-radius-3" v-for="(item, index) in psize">
            <div class="FPE-name xw-flex xw-flex-align">
              <i>型号规格</i>
              <p class="form-R form-Line xw-flex-W1 xw-Bfg"><input class="text" type="text" placeholder="" v-model.trim="item.name"/></p>
              <span class="FPE-btn fa fa-plus-square xw-color-12 xw-act" @click="getAuditFun(4, index)" v-if="Number(index) === 0"></span>
              <span class="FPE-btn fa fa-minus-square xw-color-13 xw-act" @click="getAuditFun(4, index)" v-else ></span>
            </div>
            <template v-if="isFromCloud">
              <div class="FPE-price xw-flex xw-flex-align">
                <i>销售参考价</i>
                <p class="form-R form-Line xw-flex-W1 xw-Bfg"><input class="text" type="text" placeholder="" v-model="item.price" @blur="checkLimit($event, isAmount)"/></p>
                <span>元</span>
                <span v-if="form.unitTxt">/{{form.unitTxt}}</span>
              </div>
              <div class="FPE-price xw-flex xw-flex-align">
                <i>分销进货价</i>
                <p class="form-R form-Line xw-flex-W1 xw-Bfg"><input class="text" type="text" placeholder="" v-model="item.cloudprice" @blur="checkLimit($event, isAmount)"/></p>
                <span>元</span>
                <span v-if="form.unitTxt">/{{form.unitTxt}}</span>
              </div>
            </template>
            <template v-else >
              <div class="FPE-price xw-flex xw-flex-align">
                <i>销售价格</i>
                <p class="form-R form-Line xw-flex-W1 xw-Bfg"><input class="text" type="text" placeholder="" v-model="item.price" @blur="checkLimit($event, isAmount)"/></p>
                <span>元</span>
                <span v-if="form.unitTxt">/{{form.unitTxt}}</span>
              </div>
            </template>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>备注说明</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.noteTxt"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 powerBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">商品主图</span>
              <span v-if="Number(top.maxnum) > 0">数量：最多{{top.maxnum}}张</span>
            </div>
            <dl class="FIS-img xw-float">
              <dd class="xw-float-W3" v-for="(item, index) in top.imgs"><label class="xw-block xw-act" :style="top.setTrueStyle"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.imgUrl + ')' }"></div><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, top, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, top, index)"></span></dd>
              <dd class="xw-float-W3" v-if="top.add"><label class="xw-act xw-flex xw-flex-center" :style="top.setTrueStyle" @click="uploadAct(3, top)"><em class="fal fa-plus"></em></label></dd>
            </dl>
          </div>
        </li>
        <li>
          <div class="form-editor xw-radius-3">
            <h1>详细说明</h1>
            <div ref="forEditor" v-html="form.content"></div>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 squareBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">图文详情</span>
              <span v-if="Number(fot.maxnum) > 0">数量：最多{{fot.maxnum}}张</span>
            </div>
            <dl class="FIS-img xw-float">
              <dd class="xw-float-W3" v-for="(item, index) in fot.imgs"><label class="xw-block xw-act" :style="fot.setTrueStyle"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.imgUrl + ')' }"></div><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, fot, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, fot, index)"></span></dd>
              <dd class="xw-float-W3" v-if="fot.add"><label class="xw-act xw-flex xw-flex-center" :style="fot.setTrueStyle" @click="uploadAct(3, fot)"><em class="fal fa-plus"></em></label></dd>
            </dl>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <picker-view ref="pickerCateRoot"/>
    <picker-view ref="pickerCateSon"/>
    <picker-view ref="pickerUnit"/>
    <uploadoss-view ref="uploadoss"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>